package task5;

import java.util.Random;

public class BankApp {
	private static final int DEFAULT_ACCOUNTS_NUMBER = 899;
	private static final int DEFAULT_MONEY_CEILING = 10000;
	private static final int DEFAULT_FRACTURES_IN_MONEY = 100;
	private static final int DEFAULT_THREADS_NUMBER = 3500;

	public static void main(String[] args) {
		Bank b = new Bank();
		Random r = new Random();
		Bank.Money m;

		for (int i = 0; i < DEFAULT_ACCOUNTS_NUMBER; i++) {
			m = b.new Money(r.nextInt(DEFAULT_MONEY_CEILING),
					r.nextInt(DEFAULT_FRACTURES_IN_MONEY));
			b.createAccount(i, m);
		}

		System.out.println("Starting funds in bank: "
				+ b.getTotalFundsInBank().toString());

		Thread[] transactionThreads = new Thread[DEFAULT_THREADS_NUMBER];
		for (int i = 0; i < DEFAULT_THREADS_NUMBER; i++) {
			int fromId = r.nextInt(DEFAULT_ACCOUNTS_NUMBER);
			int toId = r.nextInt(DEFAULT_ACCOUNTS_NUMBER);
			while (toId == fromId) {
				toId = r.nextInt(DEFAULT_ACCOUNTS_NUMBER);
			}
			m = b.new Money(r.nextInt(DEFAULT_MONEY_CEILING), r.nextInt(100));
			transactionThreads[i] =
					new Thread(b.new TransactionThread(fromId, toId, m));
		}

		for (int i = 0; i < DEFAULT_THREADS_NUMBER; i++) {
			transactionThreads[i].start();
		}

		for (int i = 0; i < DEFAULT_THREADS_NUMBER; i++) {
			try {
				transactionThreads[i].join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		System.out.println("Resulting funds in bank: "
				+ b.getTotalFundsInBank().toString());
	}
}